//
//  HYMyBookingDateSelectView.m
//  Booking
//
//  Created by Duntech on 2018/4/26.
//  Copyright © 2018年 Duntech. All rights reserved.
//

#import "HYMyBookingDateSelectView.h"
#import "ZJUsefulPickerView.h"
#import "HYCityModel.h"

@interface HYMyBookingDateSelectView () <PGDatePickerDelegate>

@property (nonatomic,strong) UIView *blackBgView;
@property (nonatomic,strong) UIView *selectBgView;
@property (nonatomic,strong) UIButton *statusBtn;
@property (nonatomic,strong) UIButton *locationBtn;
@property (nonatomic,strong) UIButton *startTimeBtn;
@property (nonatomic,strong) UIButton *endTimeBtn;
@property (nonatomic,strong) UIButton *searchBtn;
@property (nonatomic,assign) NSInteger selectIndex;

@property (nonatomic,assign) NSInteger status;
@property (nonatomic,copy)   NSString *cityID;
@property (nonatomic,copy)   NSString *selectCity;
@property (nonatomic,copy)   NSString *selectStartTime;
@property (nonatomic,copy)   NSString *selectEndTime;

@end

@implementation HYMyBookingDateSelectView

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setupSubviews];
        [self setupMasonryLayout];
        self.backgroundColor = KAPP_Clear_COLOR;
    }
    return self;
}

- (void)setupSubviews{
    self.status = -1;
    [self addSubview:self.blackBgView];
    [self addSubview:self.selectBgView];
    [self.selectBgView addSubview:self.statusBtn];
    [self.selectBgView addSubview:self.startTimeBtn];
    [self.selectBgView addSubview:self.endTimeBtn];
    [self.selectBgView addSubview:self.locationBtn];
    [self.selectBgView addSubview:self.searchBtn];
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
}

- (void)setupMasonryLayout{
    
    [_blackBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self);
    }];
    
    _selectBgView.frame = CGRectMake(0, 0, KSCREEN_WIDTH, 0);
    
    [_statusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self).offset(10 * WIDTH_MULTIPLE);
        make.width.mas_equalTo((KSCREEN_WIDTH - 30 * WIDTH_MULTIPLE) / 2);
        make.height.mas_equalTo(40 * WIDTH_MULTIPLE);
    }];
    
    [_locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.bottom.equalTo(self.statusBtn);
        make.left.equalTo(self.statusBtn.mas_right).offset(10 * WIDTH_MULTIPLE);
        make.right.mas_equalTo(self).offset(-10 * WIDTH_MULTIPLE);
    }];
    
    [_startTimeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.statusBtn);
        make.top.equalTo(self.statusBtn.mas_bottom).offset(10 * WIDTH_MULTIPLE);
        make.height.mas_equalTo(60 * WIDTH_MULTIPLE);
        make.width.mas_equalTo((KSCREEN_WIDTH - 30 * WIDTH_MULTIPLE) / 2);
    }];
    
    [_endTimeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.startTimeBtn.mas_right).offset(10 * WIDTH_MULTIPLE);
        make.top.bottom.equalTo(self.startTimeBtn);
        make.right.equalTo(self.locationBtn);
    }];
    
    [_searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(10 * WIDTH_MULTIPLE);
        make.right.equalTo(self).offset(-10 * WIDTH_MULTIPLE);
        make.top.equalTo(self.endTimeBtn.mas_bottom).offset(30 * WIDTH_MULTIPLE);
        make.height.mas_equalTo(50 * WIDTH_MULTIPLE);
    }];
}

#pragma mark - public
- (void)showDateCitySelectViewInView:(UIView *)view{
    
    [view addSubview:self];
    self.frame = CGRectMake(0, 60 * WIDTH_MULTIPLE, KSCREEN_WIDTH, view.height - 60 * WIDTH_MULTIPLE);
    self.blackBgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    [UIView animateWithDuration:0.2 animations:^{
        
        self.selectBgView.frame = CGRectMake(0, 0, self.width, 240 * WIDTH_MULTIPLE);
        for (UIView *subview in self.selectBgView.subviews) {
            
            subview.hidden = YES;
        }
    } completion:^(BOOL finished) {
        
        for (UIView *subview in self.selectBgView.subviews) {
            
            subview.hidden = NO;
        }
    }];
    
}

- (void)hideDateCitySelectView{
    
    [self removeFromSuperview];
}

#pragma mark - action
- (void)statusBtnAction{

    [ZJUsefulPickerView showSingleColPickerWithToolBarText:NSLocalizedString(@"selectType", nil)
                                                  withData:@[NSLocalizedString(@"confirmStatus", nil),
                                                             NSLocalizedString(@"currentStatus", nil),
                                                             NSLocalizedString(@"expiredStatus", nil),
                                                             NSLocalizedString(@"allStatus", nil)]
                                          withDefaultIndex:0 withCancelHandler:nil
                                           withDoneHandler:^(NSInteger selectedIndex, NSString *selectedValue) {
        
        self.status = selectedIndex;
        [self.statusBtn setTitle:selectedValue forState:UIControlStateNormal];
    }];
}

- (void)locationBtnAction{
    
    NSMutableArray *cityArray = [NSMutableArray array];
    NSMutableArray *cityNameArr = [NSMutableArray array];
    [HYNetRequestHandle getCityListComplection:^(NSArray *cityList) {
        
        [cityList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            HYCityModel *model = [HYCityModel modelWithDictionary:obj];
            [cityArray addObject:model];
            [cityNameArr addObject:model.name];
        }];
        
        [ZJUsefulPickerView showSingleColPickerWithToolBarText:NSLocalizedString(@"selectOffice", nil) withData:cityNameArr withDefaultIndex:0 withCancelHandler:nil withDoneHandler:^(NSInteger selectedIndex, NSString *selectedValue) {
            
            HYCityModel *cityModel = cityArray[selectedIndex];
            self.selectCity = cityModel.name;
            self.cityID = cityModel.id;
            [self.locationBtn setTitle:self.selectCity forState:UIControlStateNormal];
        }];
    }];
}

- (void)startTimeBtnAction{
    
    self.selectIndex = 1;
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc] init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.datePickerMode = PGDatePickerModeDate;
    datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:15 * 60];
    datePickManager.isShadeBackgroud = YES;
    datePickManager.titleLabel.text = NSLocalizedString(@"selectDate", nil);
    [self.viewController presentViewController:datePickManager animated:false completion:nil];
}

- (void)endTimeBtnAction{
    
    self.selectIndex = 2;
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc] init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.datePickerMode = PGDatePickerModeDate;
    datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:45 * 60];
    datePickManager.isShadeBackgroud = YES;
    datePickManager.titleLabel.text = NSLocalizedString(@"selectDate", nil);
    [self.viewController presentViewController:datePickManager animated:false completion:nil];
}

- (void)searchBtnAction{
    
    NSDate *startDate = [NSDate dateWithString:self.selectStartTime format:@"yyyy-MM-dd HH:mm"];
    NSInteger startTimestamp = [startDate timeIntervalSince1970];
    NSDate *endDate = [NSDate dateWithString:self.selectEndTime format:@"yyyy-MM-dd HH:mm"];
    NSInteger endTimeStamp = [endDate timeIntervalSince1970];
    if (endTimeStamp - startTimestamp < 0) {
        
        [JRToast showWithText:NSLocalizedString(@"startEndTimeTips", nil) duration:2];
        return;
    }
    
    if (self.MyBookingFilterSearchBlock) {
        
        self.MyBookingFilterSearchBlock(self.selectStartTime, self.selectEndTime, self.status, self.cityID,self.selectCity);
        [self hideDateCitySelectView];
    }
}

#pragma mark - PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents{
    
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *selectDate = [gregorianCalendar dateFromComponents:dateComponents];
    NSString *dateStr = [HYDateHandle getDateStringWithDate:selectDate formater:@"yyyy-MM-dd"];
    if (self.selectIndex == 1) {
        
        NSString *startDateStr = [NSString stringWithFormat:@"%@\n%@",NSLocalizedString(@"startTime", nil),dateStr];
        self.selectStartTime = [HYDateHandle getDateStringWithDate:selectDate formater:@"yyyy-MM-dd HH:mm"];
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:startDateStr attributes:@{NSFontAttributeName : KFitFont(16), NSForegroundColorAttributeName : KAPP_BLACK_COLOR}];
        NSRange range = [startDateStr rangeOfString:NSLocalizedString(@"startTime", nil)];
        [attributedStr addAttributes:@{NSForegroundColorAttributeName : KAPP_ORANGE_COLOR, NSFontAttributeName : KFitFont(14)} range:range];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:10];
        style.alignment = NSTextAlignmentCenter;
        [attributedStr addAttributes:@{NSParagraphStyleAttributeName : style} range:NSMakeRange(0, attributedStr.length)];
        [_startTimeBtn setAttributedTitle:attributedStr forState:UIControlStateNormal];
    }
    else{
        
        NSString *startDateStr = [NSString stringWithFormat:@"%@\n%@",NSLocalizedString(@"endTime", nil),dateStr];
        self.selectEndTime = [HYDateHandle getDateStringWithDate:selectDate formater:@"yyyy-MM-dd HH:mm"];
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:startDateStr attributes:@{NSFontAttributeName : KFitFont(16), NSForegroundColorAttributeName : KAPP_BLACK_COLOR}];
        NSRange range = [startDateStr rangeOfString:NSLocalizedString(@"endTime", nil)];
        [attributedStr addAttributes:@{NSForegroundColorAttributeName : KAPP_ORANGE_COLOR, NSFontAttributeName : KFitFont(14)} range:range];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:10];
        style.alignment = NSTextAlignmentCenter;
        [attributedStr addAttributes:@{NSParagraphStyleAttributeName : style} range:NSMakeRange(0, attributedStr.length)];
        [_endTimeBtn setAttributedTitle:attributedStr forState:UIControlStateNormal];
    }
}

#pragma mark - lazyload
- (UIView *)blackBgView{
    
    if (!_blackBgView) {
        _blackBgView = [UIView new];
        _blackBgView.backgroundColor = KAPP_BLACK_COLOR;
        _blackBgView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            
            CGPoint tapPoint = [sender locationInView:self];
            if (!CGRectContainsPoint(self.selectBgView.frame, tapPoint)) {
                [self hideDateCitySelectView];
            }
            
        }];
        [_blackBgView addGestureRecognizer:tapGes];
    }
    return _blackBgView;
}



- (UIView *)selectBgView{
    
    if (!_selectBgView) {
        
        _selectBgView = [UIView new];
        _selectBgView.backgroundColor = KCOLOR(@"e1e1e1");
    }
    return _selectBgView;
}

- (UIButton *)statusBtn{
    
    if (!_statusBtn) {
        _statusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _statusBtn.titleLabel.font = KFitFont(16);
        _statusBtn.backgroundColor = KAPP_WHITE_COLOR;
        [_statusBtn setTitleColor:KAPP_BLACK_COLOR forState:UIControlStateNormal];
        [_statusBtn addTarget:self action:@selector(statusBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_statusBtn setTitle:NSLocalizedString(@"allBookings", nil) forState:UIControlStateNormal];
    }
    return _statusBtn;
}

- (UIButton *)locationBtn{
    
    if (!_locationBtn) {
        _locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _locationBtn.titleLabel.font = KFitFont(16);
        _locationBtn.backgroundColor = KAPP_WHITE_COLOR;
        [_locationBtn setTitleColor:KAPP_BLACK_COLOR forState:UIControlStateNormal];
        [_locationBtn addTarget:self action:@selector(locationBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_locationBtn setTitle:NSLocalizedString(@"allOffices", nil) forState:UIControlStateNormal];
    }
    return _locationBtn;
}

- (UIButton *)startTimeBtn{
    
    if (!_startTimeBtn) {
        
        _startTimeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _startTimeBtn.backgroundColor = KAPP_WHITE_COLOR;
        _startTimeBtn.titleLabel.numberOfLines = 0;
    
        NSString *startDateStr = [NSString stringWithFormat:@"%@\n%@",NSLocalizedString(@"startTime", nil),[HYDateHandle getCurrentDateStrDDMMYYYYWithTimeInterval:0]];
        self.selectStartTime = [HYDateHandle getCurrentDateStrYYYYMMddHHmmWithTimeInterval:0];
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:startDateStr attributes:@{NSFontAttributeName : KFitFont(16), NSForegroundColorAttributeName : KAPP_BLACK_COLOR}];
        NSRange range = [startDateStr rangeOfString:NSLocalizedString(@"startTime", nil)];
        [attributedStr addAttributes:@{NSForegroundColorAttributeName : KAPP_ORANGE_COLOR, NSFontAttributeName : KFitFont(14)} range:range];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:10];
        style.alignment = NSTextAlignmentCenter;
        [attributedStr addAttributes:@{NSParagraphStyleAttributeName : style} range:NSMakeRange(0, attributedStr.length)];
        [_startTimeBtn setAttributedTitle:attributedStr forState:UIControlStateNormal];
        [_startTimeBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
//        _startTimeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_startTimeBtn addTarget:self action:@selector(startTimeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _startTimeBtn;
}

- (UIButton *)endTimeBtn{
    
    if (!_endTimeBtn) {
        
        _endTimeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _endTimeBtn.backgroundColor = KAPP_WHITE_COLOR;
        _endTimeBtn.titleLabel.numberOfLines = 0;
        NSString *startDateStr = [NSString stringWithFormat:@"%@\n%@",NSLocalizedString(@"endTime", nil),[HYDateHandle getCurrentDateStrDDMMYYYYWithTimeInterval:7 * 24 * 60 * 60]];
        self.selectEndTime = [HYDateHandle getCurrentDateStrYYYYMMddHHmmWithTimeInterval:7 * 24 * 60 * 60];
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:startDateStr attributes:@{NSFontAttributeName : KFitFont(16), NSForegroundColorAttributeName : KAPP_BLACK_COLOR}];
        NSRange range = [startDateStr rangeOfString:NSLocalizedString(@"endTime", nil)];
        [attributedStr addAttributes:@{NSForegroundColorAttributeName : KAPP_ORANGE_COLOR, NSFontAttributeName : KFitFont(14)} range:range];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:10];
        style.alignment = NSTextAlignmentCenter;
        [attributedStr addAttributes:@{NSParagraphStyleAttributeName : style} range:NSMakeRange(0, attributedStr.length)];
        [_endTimeBtn setAttributedTitle:attributedStr forState:UIControlStateNormal];
        
        _endTimeBtn.titleLabel.textAlignment = NSTextAlignmentRight;
        [_endTimeBtn addTarget:self action:@selector(endTimeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endTimeBtn;
}

- (UIButton *)searchBtn{
    
    if (!_searchBtn) {
        
        _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _searchBtn.backgroundColor = KAPP_WHITE_COLOR;
        [_searchBtn setTitle:NSLocalizedString(@"search", nil) forState:UIControlStateNormal];
        [_searchBtn setTitleColor:KAPP_BLACK_COLOR forState:UIControlStateNormal];
        _searchBtn.titleLabel.font = KFitFont(18);
        [_searchBtn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchBtn;
}

@end
